package com.maisonliberte.crawller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.maisonliberte.dao.Dao;
import com.maisonliberte.entity.ImageInfo;
import com.maisonliberte.entity.PriceInfo;
import com.maisonliberte.entity.ProductInfo;
import com.maisonliberte.entity.TableInfo;
import com.maisonliberte.entity.TableOtherInfo;
import com.maisonliberte.enums.ImageSizeEnum;
import com.maisonliberte.util.CalUtil;
import com.maisonliberte.util.HtmlUtil;
import com.maisonliberte.util.HttpUtil;
import com.maisonliberte.util.TranslateUtil;
import com.maisonliberte.util.WeightUtil;

public class MinneCrawler extends AbstractCrawler {

	@Override
	public String getNextPage(String data) throws Exception {
		
//		if(url.indexOf("page=") > -1){
//			return "";
//		}
//		
//		if(data.indexOf("<div class=\"minne_pagination\">") > -1){
//			String tmp = data.substring(data.indexOf("<div class=\"minne_pagination\">"));
//			tmp = tmp.substring(0, tmp.indexOf("</div>"));
//			tmp = tmp.substring(tmp.indexOf("<span class=\"next\">"));
//			tmp = tmp.substring(0, tmp.indexOf("</span>"));
//			tmp = HtmlUtil.getHrefOfATag(tmp, "rel=");
//			
//			if(!tmp.isEmpty()){
//				url = String.format("http://www.minne.com%s", tmp).replace("&amp;", "&");
//				return url;
//			}
//				
//			
//			return tmp;
//		}
		
		return "";
	}

	@Override
	public void analyzeParsedData(String data) throws Exception {
		// TODO Auto-generated method stub
		try{
			String body = data.substring(data.indexOf("<ul class=\"item_list\">") + String.valueOf("<ul class=\"item_list\">").length());
			body = body.substring(0, body.indexOf("</ul>"));
			
			String startTag = "<li>";
			String endTag = "</li>";
			
			while(true){				
				if(body.indexOf(startTag) == -1) break;
				String block = body.substring(body.indexOf(startTag));
				block = block.substring(0, block.indexOf(endTag) + String.valueOf(endTag).length());
				body = body.replace(block, "");	
				this.parsingDataList.add(block);
				//break;
			}

			
		}catch(Exception ex){
			System.out.println("analyzeParsedData " + ex.getMessage());
			System.out.println("parsingDataList : " + parsingDataList.size());
			throw ex;
		}
	}

	@Override
	public String getDetailUrl(String data) throws Exception {
		try{
			//<a class="fadeimg" href="/mojo/ProductInfo/sku/KA143-42-0000-0064/">
			//getHrefOfATag
			String tmp = data.substring(data.indexOf("<dt>"));
			tmp = tmp.substring(0, tmp.indexOf("</dt>")+String.valueOf("</dt>").length());
			String url = HtmlUtil.getHrefOfATag(tmp, "\">");
			if(url.indexOf("http://www.minne.com/") == -1){
				url = String.format("http://www.minne.com%s", url);
			}
			
			if(Dao.getInstance().isDuplicateProduct(url)){
				return null;
			}
			
			return url;
			
		}catch(Exception ex){
			System.out.print(data);
			System.out.println("getDetailUrl" + ex.getMessage());
			throw ex;
		}
	}

	@Override
	public void analyzerProductDetailInfo(String data, ProductInfo pInfo)
			throws Exception {
		String url = "";
		String productName = "";
		String weight = "";
		String spec = "";
		String qty = "";
		int price = 0;
		
		try{
			
			TableInfo prodTable = new TableInfo();
			TableOtherInfo prodTableOther = new TableOtherInfo();
			pInfo.setTableInfo(prodTable);
			pInfo.setTableOther(prodTableOther);
			prodTable.setCate(this.category.value());
			prodTable.setForwardFee(true);
			//prodTable.setNumber(Dao.getInstance().getNewProductNumber());
			
			//URL
			String tmp = data.substring(data.indexOf("<meta property=\"og:url\""));
			String tmp_sub = tmp.substring(0, tmp.indexOf("/>") + String.valueOf("/>").length());
			tmp_sub = tmp_sub.substring(tmp_sub.indexOf("content=") + String.valueOf("content=").length());
			tmp_sub = tmp_sub.substring(0, tmp_sub.indexOf("/>"));
			url = tmp_sub.replace("\"", "").trim();
			prodTable.setSourceUrl(url);
			
			//productName
			tmp = data.substring(data.indexOf("<div id=\"main\" class=\"gellery_d_l\">"));
			tmp_sub = tmp.substring(0, tmp.indexOf("<!-- Start Advanced Gallery Html Containers -->"));
			tmp_sub = tmp_sub.substring(tmp_sub.indexOf("<h1>"));
			tmp_sub = tmp_sub.substring(0, tmp_sub.indexOf("</h1>"));
			productName = tmp_sub.replace("<h1>", "").replace("</h1>", "");
			prodTable.setName_jp(productName);
			prodTable.setName(TranslateUtil.translateJpnToKor(productName));
			
			tmp = data.substring(data.indexOf("<table class=\"item_spec\">"));
			tmp = tmp.substring(0, tmp.indexOf("</table>") + String.valueOf("</table>").length());
			
			//購入の際の注意点
			if(tmp.indexOf("<th>購入の際の注意点</th>") > -1){
				tmp_sub = tmp.substring(tmp.indexOf("<th>購入の際の注意点</th>"));
				tmp_sub = tmp_sub.substring(0, tmp_sub.indexOf("</tr>") + String.valueOf("</tr>").length());
				tmp_sub = tmp_sub.substring(tmp_sub.indexOf("<td>") + String.valueOf("<td>").length());
				tmp_sub = tmp_sub.substring(0, tmp_sub.indexOf("</td>"));
				prodTableOther.setStaff_comment_jpn(tmp_sub);
				prodTableOther.setStaff_comment(TranslateUtil.translateJpnToKor(tmp_sub));
			}
			// 在庫
			qty = "6";
			prodTable.setQty(Integer.valueOf(qty));
			
			//サイズ
			if(tmp.indexOf("<th>サイズ</th>") > -1){
				tmp_sub = tmp.substring(tmp.indexOf("<th>サイズ</th>"));
				tmp_sub = tmp_sub.substring(0, tmp_sub.indexOf("</tr>") + String.valueOf("</tr>").length());
				tmp_sub = tmp_sub.substring(tmp_sub.indexOf("<td>") + String.valueOf("<td>").length());
				tmp_sub = tmp_sub.substring(0, tmp_sub.indexOf("</td>"));
				spec = "■사이즈:" + TranslateUtil.translateJpnToKor(tmp_sub) + "<br>";
			}
			
			//発送までの日数の目安
			if(tmp.indexOf("<th>発送までの日数の目安</th>") > -1){
				tmp_sub = tmp.substring(tmp.indexOf("<th>発送までの日数の目安</th>"));
				tmp_sub = tmp_sub.substring(0, tmp_sub.indexOf("</tr>") + String.valueOf("</tr>").length());
				tmp_sub = tmp_sub.substring(tmp_sub.indexOf("<td>") + String.valueOf("<td>").length());
				tmp_sub = tmp_sub.substring(0, tmp_sub.indexOf("</td>"));
 				int days = Integer.valueOf(tmp_sub) + 4;
				spec += "■배송까지 걸리는 기간:" + String.format("%d일", days) + "<br>";
			}
			
			//prodTable.setExplan_jpn(spec);
			prodTable.setExplan(spec);
			//prodTable.setExplan(TranslateUtil.translateJpnToKor(prodTable.getExplan_jpn()));
			
			// 送料
			String localCarriage = "0"; 
			if(tmp.indexOf("<th>送料</th>") > -1){
				tmp_sub = tmp.substring(tmp.indexOf("<th>送料</th>"));
				tmp_sub = tmp_sub.substring(0, tmp_sub.indexOf("</tr>") + String.valueOf("</tr>").length());
				tmp_sub = tmp_sub.substring(tmp_sub.indexOf("<td>") + String.valueOf("<td>").length());
				tmp_sub = tmp_sub.substring(0, tmp_sub.indexOf("</td>"));
				tmp_sub = tmp_sub.replace("円", "");
				localCarriage = tmp_sub.replace(",", "");
			}


			// 価格
			tmp = data.substring(data.indexOf("<div class=\"sell_frame\">"));
			tmp = tmp.substring(0, tmp.indexOf("</div>"));
			tmp_sub = tmp.substring(tmp.indexOf("<span class=\"font_size_l strong\">"));
			tmp_sub = tmp_sub.substring(0, tmp_sub.indexOf("</span>") + String.valueOf("</span>").length());
			tmp_sub = tmp_sub.replace("<span class='font_10'> (税込)", "");
			tmp_sub = tmp_sub.replace("</span>", "");
			tmp_sub = tmp_sub.replace("<span class=\"font_size_l strong\">", "");
			tmp_sub = tmp_sub.replace("円", "");
			tmp_sub = tmp_sub.replace(",", "");
			String orgPrice = tmp_sub;
			price = 0;
			
			weight = WeightUtil.getWeight(this.category);
			PriceInfo priceInfo = CalUtil.getPrice(Integer.valueOf(orgPrice), Integer.valueOf(localCarriage), Integer.valueOf(weight));
			pInfo.setPriceInfo(priceInfo);
			prodTable.setPrice(priceInfo.Price());
			prodTable.setConsumerPrice(priceInfo.ConPrice());
			prodTable.setCarriage(String.valueOf(priceInfo.getEmsFee()));
			
			// SELECTOR
			boolean isLong = false;
			boolean isFunction = false;
			boolean isDesign = false;
			boolean isEcho = false;
			boolean isTradition = false;
			boolean isRare = false;
			prodTableOther.setS_long(isLong ? 1 : 0);
			prodTableOther.setS_function(isFunction ? 1 : 0);
			prodTableOther.setS_design(isDesign ? 1 : 0);
			prodTableOther.setS_echo(isEcho ? 1 : 0);
			prodTableOther.setS_tradition(isTradition ? 1 : 0);
			prodTableOther.setS_rare(isRare ? 1 : 0);
			prodTableOther.setStaff_id("M99999");
			prodTableOther.setMaker_id("M99999");
			prodTableOther.setBrand_id("M99999");
			
			System.out.println(String.format("product name : %s parsing end", prodTable.getSourceUrl()));
			
		
		}catch(Exception ex){
			System.out.println("[analyzerProductDetailInfo][url] " + url);
			System.out.println("[analyzerProductDetailInfo][weight] " + weight);
			System.out.println("[analyzerProductDetailInfo][spec] " + spec);
			System.out.println("[analyzerProductDetailInfo][qty] " + qty);
			System.out.println("[analyzerProductDetailInfo][price] " + price);
			System.out.println("[analyzerProductDetailInfo]" + ex.getMessage());
			throw ex;
		}
		
	}

	@Override
	public void analyzerImageInfo(String data, ProductInfo pInfo)
			throws Exception {
		try{
			
			Map<ImageSizeEnum, List<ImageInfo>> imageList = new HashMap<ImageSizeEnum, List<ImageInfo>>();
			String tmp = data;
			String tmp_sub = "";
			String mainImg = "";
			String middleImg = "";
			String listImg = "";
			String displayImg = "";
			String smallImg = "";
			List<String> otherImg = new ArrayList<String>();
			List<String> detailImg = new ArrayList<String>();
			
			//상품 이미지 Large
			if(data.indexOf(" <div id=\"thumbs\">") > -1){
				tmp = tmp.substring(tmp.indexOf("<div id=\"thumbs\">"));
				tmp = tmp.substring(0, tmp.indexOf("</div>") + String.valueOf("</div>").length());
				int i = 0;
				while(tmp.indexOf("<li>") > -1){
					tmp_sub = tmp.substring(tmp.indexOf("<li>"));
					tmp_sub = tmp_sub.substring(0, tmp_sub.indexOf("</li>") + String.valueOf("</li>").length());
					tmp = tmp.replace(tmp_sub, "");
					
					if(i == 0){
						mainImg = HtmlUtil.getHrefOfATag(tmp_sub, "class=");
						if(mainImg.indexOf("http:") == -1){
							mainImg = "http:" + mainImg;
						}
					}else{
						String tmpImg = HtmlUtil.getHrefOfATag(tmp_sub, "class=");
						if(tmpImg.indexOf("http:") == -1){
							tmpImg = "http:" + tmpImg;
						}
						detailImg.add(tmpImg);
					}
					i++;
				}
			}
			
			String productCode = getProductCode(data);
			// LARGE
			imageList.put(ImageSizeEnum.LARGE_500px, new ArrayList<ImageInfo>());
			ImageInfo imgInfo = new ImageInfo(mainImg);
			imgInfo.setCode(productCode);
			if(!mainImg.trim().isEmpty()){
				imageList.get(ImageSizeEnum.LARGE_500px).add(imgInfo);	
			}
			
			//middle
			imageList.put(ImageSizeEnum.MIDDLE_250px, new ArrayList<ImageInfo>());
			if(!middleImg.isEmpty()){
				ImageInfo middelImgInfo = new ImageInfo(middleImg);
				imgInfo.setCode(productCode);
				imageList.get(ImageSizeEnum.MIDDLE_250px).add(middelImgInfo);
			}
			
			//list
			imageList.put(ImageSizeEnum.LIST_150px, new ArrayList<ImageInfo>());
			if(pInfo.getListImg() != null){
				listImg = pInfo.getListImg(); 
			}
			
			if(!listImg.isEmpty()){
				ImageInfo listImgInfo = new ImageInfo(listImg);
				imgInfo.setCode(productCode);
				imageList.get(ImageSizeEnum.LIST_150px).add(listImgInfo);
			}
			
			//display
			imageList.put(ImageSizeEnum.DISPLAY_120px, new ArrayList<ImageInfo>());
			if(!displayImg.isEmpty()){
				ImageInfo disImgInfo = new ImageInfo(displayImg);
				imgInfo.setCode(productCode);
				imageList.get(ImageSizeEnum.DISPLAY_120px).add(disImgInfo);
			}
			
			//small
			imageList.put(ImageSizeEnum.SMALL_80px, new ArrayList<ImageInfo>());
			if(!displayImg.isEmpty()){
				ImageInfo smallImgInfo = new ImageInfo(smallImg);
				imgInfo.setCode(productCode);
				imageList.get(ImageSizeEnum.SMALL_80px).add(smallImgInfo);
			}
			
			// OTHER OTHER
			imageList.put(ImageSizeEnum.OTHER_IMG, new ArrayList<ImageInfo>());
			for(String src : otherImg){
				ImageInfo otherImgInfo = new ImageInfo(src);
				imgInfo.setCode(productCode);
				imageList.get(ImageSizeEnum.OTHER_IMG).add(otherImgInfo);
			}
			
			// DETAIL
			imageList.put(ImageSizeEnum.DETAIL_IMG, new ArrayList<ImageInfo>());
			for(String src : detailImg){
				ImageInfo detailImgInfo = new ImageInfo(src);
				imgInfo.setCode(productCode);
				imageList.get(ImageSizeEnum.DETAIL_IMG).add(detailImgInfo);
			}
			
			pInfo.setImageList(imageList);

			
		}catch(Exception ex){
			System.out.println("analyzerImageInfo" + ex.getMessage());
			System.out.println(data);
			throw ex;
		}
		
	}

	@Override
	public String requestDetailUrl(String url) throws Exception {
		return HttpUtil.httpGet(url, "utf-8");
	}

	@Override
	protected String getProductCode(String data){
		//<meta property="og:url" content="http://www.minne.com/sunny-craft/item/76890" />
		String tmp = data.substring(data.indexOf("<meta property=\"og:url\""));
		tmp = tmp.substring(0, tmp.indexOf(">") + 1);
		tmp = tmp.substring(tmp.indexOf("content=") + String.valueOf("content=").length());
		tmp = tmp.substring(0, tmp.indexOf("/>"));
		tmp = tmp.replace("\"", "").replace("http://www.minne.com/", "").replace("/item/", "").replace("items", "").replace("/", "");
		tmp = tmp.toUpperCase();
		return tmp.trim();
	}

	@Override
	protected String getListImg(String data) {
		String tmp = data.substring(data.indexOf("<img"));
		tmp = tmp.substring(0, tmp.indexOf("/>") + String.valueOf("/>").length());
		tmp = HtmlUtil.getImageSrcOfImgTag(tmp, "width=");
		if(tmp.indexOf("http:") == -1){
			tmp = "http:" + tmp;
		}
		if(tmp.equals("http://www.minne.com/images/model/photo/medium.gif?1360653321")){
			return null;
		}		
		return tmp;
	}

}
